export function parseDom(html) {
  let ele = document.createElement('div')
  ele.innerHTML = html
  return ele.childNodes[0]
}

export default class CCH5BulletScreenComponent {
  /**
   * @constructor cc播放器跑马灯构造函数
   * @param {String player 父节点}
   * @param {String text 跑马灯内容}
   * @param {Object style 跑马灯样式}
   * param {String bulletPosition 跑马灯所在的位置, 可能的值 'top', 'bottom' , 'random, 默认为 'random'}
   * param {String frequency 间隔多少秒跑一次}
   */
  constructor(player, text, style, bulletPosition = 'random', frequency = 0) {
    this.playerHTML = document.querySelector(player)
    this.text = text
    this.style = style || { fontSize: '14px', color: '#fff' }
    this.html = parseDom('<div class="bullet-screen"></div>')
    this.bulletPosition = bulletPosition
    this.frequency = frequency
    this.html.style.animationDelay = `${frequency}s`
  }

  ready() {
    this.html.innerText = this.text
    this.playerHTML.appendChild(this.html)

    Object.keys(this.style).forEach((key) => (this.html.style[key] = this.style[key]))

    //字体高度
    var bulletHeight = this.html.offsetHeight

    //播放器高度
    var playerHeight = this.playerHTML.offsetHeight

    //字体距离播放器底部最大高度
    var maxHeight = playerHeight - bulletHeight

    if (this.bulletPosition === 'bottom') {
      this.html.style.bottom = 0
    } else {
      let top = this.bulletPosition === 'top' ? '40px' : this.randomTop(maxHeight)
      this.html.style.top = top
    }

    if (this.bulletPosition === 'random') {
      this.html.addEventListener('animationiteration', () => {
        this.html.style.top = this.randomTop(maxHeight)
      })
    }

    // 设置间隔
    this.html.addEventListener('animationiteration', () => {
      this.html.style.animationPlayState = 'paused'
      setTimeout(() => {
        this.html.style.animationPlayState = 'running'
      }, this.frequency * 1000)
    })
  }

  playing() {
    console.log('play')
    this.html.style.animationPlayState = 'running'
  }

  pause() {
    console.log('pause')
    // this.html.style.animationPlayState = 'paused'
  }

  randomTop(max) {
    return Math.floor(Math.random() * max) + 'px'
  }
}
